package com.atguigu.collect.service.impl;

import com.atguigu.clients.ProductClient;
import com.atguigu.collect.mapper.CollectMapper;
import com.atguigu.collect.service.CollectService;
import com.atguigu.param.ProductIdsParam;
import com.atguigu.pojo.Collect;
import com.atguigu.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class CollectServiceImpl implements CollectService {

    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private ProductClient productClient;

    @Override
    public R save(Collect collect) {

        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",collect.getUserId());
        queryWrapper.eq("product_id",collect.getProductId());
        Long count = collectMapper.selectCount(queryWrapper);
        if(count>0){
            return R.fail("该用户已收藏该商品，无需二次收藏");
        }
        // 设置收藏时间字段
        collect.setCollectTime(System.currentTimeMillis());
        int rows = collectMapper.insert(collect);
        return R.ok("收藏插入成功");
    }

    @Override
    public R list(Collect collect) {

        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",collect.getUserId());
        queryWrapper.select("product_id");
        List<Object> productIds = collectMapper.selectObjs(queryWrapper);

        Integer[] idsArray = productIds.toArray(new Integer[]{});
//        ArrayList<Integer> ids = new ArrayList<>();
        List<Integer> ids = Arrays.asList(idsArray);


        ProductIdsParam productIdsParam = new ProductIdsParam();
        productIdsParam.setProductIds(ids);

        return productClient.ids(productIdsParam);

    }

    @Override
    public R remove(Collect collect) {

        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",collect.getUserId());
        queryWrapper.eq("product_id",collect.getProductId());
        int rows = collectMapper.delete(queryWrapper);
        return R.ok("删除收藏成功");
    }
}
